package cn.tedu._05weibo.controller;

import cn.tedu._05weibo.mapper.UserMapper;
import cn.tedu._05weibo.pojo.dto.UserLoginDTO;
import cn.tedu._05weibo.pojo.dto.UserRegDTO;
import cn.tedu._05weibo.pojo.entity.User;
import cn.tedu._05weibo.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/v1/users/")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("reg")
    public int reg(@RequestBody UserRegDTO userRegDTO) {
        /*
        1.接收客户端传递的数据;
        2.校验数据的合法性[暂时不校验];
        3.校验用户名是否被占用[SELECT接口];
            3.1 被占用,retrun 2;
            3.2 没被占用,插入数据[INSERT接口],return 1;
         */
        System.out.println("userRegDTO = " + userRegDTO);
       UserVO userVO=userMapper.selectByUsername(userRegDTO.getUsername());
        if (userVO != null) {
            return 2;
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO, user);
        user.setCreated(new Date());
        userMapper.insertUser(user);
        return 1;

    }
    @PostMapping("login")
    public int login(@RequestBody UserLoginDTO userLoginDTO, HttpSession session){
        /**
         * 1.接收客户端传递的数据;
         * 2.查询用户名是否正确
         * 3.校验密码是否正确
         * 4.返回结果
         */
        UserVO userVO = userMapper.selectByUsername(userLoginDTO.getUsername());
        if (userVO == null) {
            return 3;
        }
        if (userVO.getPassword().equals(userLoginDTO.getPassword())){
            //登陆成功，保存用户的会话
            session.setAttribute("user",userVO);
            return 1;
        }
        //密码错误
        return 2;

    }
    /**
     * 3.获取当前登录用户的信息
     */
    @GetMapping("currentUser")
    public UserVO currentUser(HttpSession session){
        UserVO userVO= (UserVO) session.getAttribute("user");
        return userVO;
    }
    /**
     * 4.退出登录
     */
    @GetMapping("logout")
    public void logout(HttpSession session){
        //z在服务器内存中删除会话对象
        session.removeAttribute("user");
    }


}
